function toGetUrl(url: string, params: any) {
  var idx: number = url.indexOf('?');
  if (idx < 0) {
    url = url + '?';
  }
  for (var key in params) {
    if (params.hasOwnProperty(key)) {
      var v = params[key];
      if (v !== '') {
        url += key + '=' + params[key] + '&';
      }
    }
  }
  url = url.substr(0, url.length - 1);
  return url;
};


let strategyKey: any[] = [
  {
    type: 'toutiao',
    url: 'http://v.juhe.cn/toutiao/index',
    data: {
      key: '00cb2c7176a328850e5f6789abddb91b'
    }
  },
  {
    type: 'mobile',
    url: 'http://apis.juhe.cn/mobile/get',
    data: {
      key: 'bd2ee1c03f99b17c6c7d71513298cb1c'
    }
  },
  {
    type: 'ip',
    url: 'http://apis.juhe.cn/ip/ipNew',
    data: {
      key: 'f597644bfde992f313eee8628fc823c4'
    }
  }
]

const request = (type: string, data: any, isLoading: boolean = true) => {
  if (isLoading) {
    wx.showLoading({
      title: '加载中'
    });
  }
  var promise = new Promise(function (resolve: any, reject: any) {
    let param = strategyKey.find((value: any) => type == value.type) || {}
    if (param) {
      let paramData = Object.assign(data, param.data)
      let interfaceUrl = param.url
      wx.request({
        url: toGetUrl(interfaceUrl, paramData),
        method: "GET",
        header: {
          "Content-Type": "application/json;charset=UTF-8"
        },
        success: function (res) {
          if (isLoading) {
            wx.hideLoading();
          }
          if (res.statusCode) {
            let info: any = res.data
            if (info.error_code == 0) {
              resolve(info.result);
            } else {
              wx.showToast({
                title: info.reason,
                icon: 'none'
              })
              reject({
                code: info.resultcode,
                msg: info.reason
              });
            }
          } else {
            reject({
              code: 333,
              msg: "网络错误"
            });
          }
        },
        fail: function () {
          wx.hideLoading();
        }
      })
    }
  });
  return promise;
}

export {
  request
}